//
//  XTEmoticonToolBar.swift
//  Weibo(Swift)
//
//  Created by 肖霆 on 16/5/21.
//  Copyright © 2016年 肖霆. All rights reserved.
//

import UIKit

enum XTEmoticonToolBarBtnType:Int{
    case Normal = 1000
    case Emoji = 1001
    case Lxh = 1002

}
class XTEmoticonToolBar: UIStackView {

    var lastSelectedBtn:UIButton?
    //点击toolBarBtn的闭包
    var emoticonToolBarBtnClickClosure:((btnType:XTEmoticonToolBarBtnType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    private func setupUI(){
        //布局方式
        axis = .Horizontal
        distribution = .FillEqually
        
        addChildBtn("默认", backgroundImgName: "compose_emotion_table_left", btnType: .Normal)
        addChildBtn("Emoji", backgroundImgName: "compose_emotion_table_mid", btnType: .Emoji)
        addChildBtn("浪小花", backgroundImgName: "compose_emotion_table_right", btnType: .Lxh)
    
    }
    
        //  MARK: -创建并添加按钮的方法-
    private func addChildBtn(title:String,backgroundImgName:String,btnType:XTEmoticonToolBarBtnType){
        let btn = UIButton()
        btn.setTitle(title, forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "\(backgroundImgName)_normal"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "\(backgroundImgName)_selected"), forState: .Selected)
        btn.tag = btnType.rawValue
        btn.addTarget(self, action: "emoticonTypeBtnClick:", forControlEvents: .TouchUpInside)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.setTitleColor(UIColor.grayColor(), forState: .Selected)
        btn.titleLabel?.font = UIFont.systemFontOfSize(15)
        btn.adjustsImageWhenHighlighted = false
    
        //设置默认的选中项
        if btnType == .Normal{
            lastSelectedBtn?.selected = false
            btn.selected = true
            lastSelectedBtn = btn
        }
        addArrangedSubview(btn)
    }
    
        //  MARK: -点击方法-
    @objc private func emoticonTypeBtnClick(btn:UIButton){
        //如果
        if btn == lastSelectedBtn{
            return
        }
        //取消上一次点击的按钮的选中状态
        lastSelectedBtn?.selected = false
        //将点击的按钮设为选中状态
        btn.selected = true
        
        lastSelectedBtn = btn
        
        let type:XTEmoticonToolBarBtnType = XTEmoticonToolBarBtnType(rawValue: btn.tag)!
        
        emoticonToolBarBtnClickClosure?(btnType:type)
    
    }
    
    //自动切换表情键盘下面的按钮的方法
    func changeEmoticonBtnWithSection(section:Int){
        
        if section + 1000 == lastSelectedBtn?.tag {
            return
        }
        
        let btn = viewWithTag(1000+section) as? UIButton
        lastSelectedBtn?.selected = false
        btn?.selected = true
        lastSelectedBtn = btn
    }
}
